import java.util.Arrays;

public class TestHeap {
    public  int[] elem;
    public  int usedSize;

    public TestHeap() {
        this.elem = new int[10];
    }

    public void initElem(int[] array) {
        for (int i = 0; i < array.length; i++) {
            elem[i] = array[i];
            usedSize++;
        }
    }

    public void createHeap() {
        for (int parent = (usedSize - 1 - 1) / 2; parent >= 0; parent--) {
            AdjustDown(parent, usedSize);
        }
    }

    private void AdjustDown(int parent, int len) {
        int child = parent * 2 + 1;
        //建大堆
        while (child < len) {
            if (elem[child] < elem[child + 1] && child + 1 < len) {
                child++;
            }
            if (elem[parent] < elem[child]) {
                //交换
                swap(parent, child);
                parent = child;
                child = parent * 2 + 1;
            } else {
                break;
            }
        }
    }

    private void swap(int a, int b) {
        int tmp = elem[a];
        elem[a] = elem[b];
        elem[b] = tmp;
    }

    //添加元素
    public void push(int val) {
        //判断满没满
        if (isFull()) {
            //扩容
            elem = Arrays.copyOf(elem, 2 * elem.length);
        }
        elem[usedSize] = val;
        //向上调整
        setUp(usedSize);
        usedSize++;
    }
    public boolean isFull() {
        return usedSize == elem.length;
    }

    private void setUp(int child) {
        int parent = (child - 1) / 2;
        while (parent >= 0) {
            if (elem[parent] < elem[child]) {
                //交换
                swap(parent, child);
                child = parent;
                parent = (child - 1) / 2;
            } else {
                break;
            }
        }
    }

    //删除元素
    public int pop() {
        //这里默认头删
        if (empty()) {
            return -1;
        }
        //直接把第一个和最后一个交换，之后调整
        int oldVal = elem[0];
        swap(0, usedSize - 1);
        usedSize--;
        AdjustDown(0, usedSize);
        return oldVal;
    }
    public boolean empty() {
        return usedSize == 0;
    }
}
